package com.appspot.simplebookmarks.controller.bookmark;

import java.util.List;

import org.slim3.controller.Controller;
import org.slim3.controller.Navigation;

import com.appspot.simplebookmarks.model.Collection;
import com.appspot.simplebookmarks.service.CollectionService;
import com.appspot.simplebookmarks.service.LastAccessCollectionService;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

public class CreateController extends Controller {

    //Collectionを操作するサービス
    private CollectionService service = new CollectionService();

    //LastAccessCollectionを操作するサービス
    private LastAccessCollectionService lastAccessCollectionService = new LastAccessCollectionService();
    
    @Override
    public Navigation run() throws Exception {

        //ユーザー情報取得とログインチェック
        UserService userService = UserServiceFactory.getUserService();
        User user = userService.getCurrentUser();
        if (user == null) {
            return redirect(userService.createLoginURL("/bookmark/create"));
        }

        //コレクション取得
        List<Collection> collections = service.getList(user.getEmail());

        //デフォルト選択のコレクションを設定
        Key key = lastAccessCollectionService.getCurrentCollectionKey(user.getEmail());

        //jspへ値を渡す
        requestScope("author", user.getEmail());
        requestScope("collections", collections);
        requestScope("c", KeyFactory.keyToString((Key) key));

        return forward("create.jsp");
    }
}
